from sklearn.datasets import load_breast_cancer
import numpy as np
import matplotlib.pyplot as plt

def model(x,theta):
    return x.dot(theta)

def sigmoid(z):
    return 1/(1+np.exp(-z))

def cost(h,y):
    m=len(y)
    return -1/m*np.sum(y*np.log(h)+(1-y)*np.log(1-h))

def grad(x,y,iter0=5000,alpha=0.01):
    m,n=x.shape
    theta=np.zeros(n)
    J=np.zeros(iter0)
    for i in range(iter0):
        z=model(x,theta)
        h=sigmoid(z)
        J[i]=cost(h,y)
        dt=1/m*x.T.dot(h-y)
        theta-=alpha*dt
    return h,theta,J
#准确率
def score(h,y):
    return np.mean(y==[h>0.5])

if __name__ == '__main__':
    #乳腺癌数据集
    cancer = load_breast_cancer()
    # 特征
    x = cancer.data
    # 标签
    y = cancer.target

    miu=np.mean(x,axis=0)
    sigma=np.std(x,axis=0)
    x=(x-miu)/sigma

    X=np.c_[np.ones(len(x)),x]

    np.random.seed(666)
    a=np.random.permutation(len(x))
    X=X[a]
    y=y[a]

    num=int(0.7*len(x))
    train_x,test_x=np.split(X,[num,])
    train_y,test_y=np.split(y,[num,])

    train_h,theta,J=grad(train_x,train_y)
    plt.plot(J)
    plt.show()

    print('训练集准确率',score(train_h,train_y))
    z=model(test_x,theta)
    test_h=sigmoid(z)
    print('测试集准确率',score(test_h,test_y))